package com.itheima.stock.service.imp;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.stock.common.domian.StockUpdownDomain;
import com.itheima.stock.mapper.StockRtInfoMapper;
import com.itheima.stock.service.Stock_rtService;
import com.itheima.stock.utils.DateTimeUtil;
import com.itheima.stock.vo.code.ResponseCode;
import com.itheima.stock.vo.resp.PageResult;
import com.itheima.stock.vo.result.R;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.rmi.MarshalledObject;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: siwukun
 * @date: 2022/06/01
 * @description:
 */
@Service
@Slf4j
public class Stock_rtServiceImpl implements Stock_rtService {

    @Autowired
    private StockRtInfoMapper stockRtInfoMapper;

    Date lastDate = null;

    {
        lastDate = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
        lastDate = DateTime.parse("2021-12-30 09:42:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
    }

    /**
     * 涨幅榜
     *
     * @return
     */
    @Override
    public R<List<StockUpdownDomain>> queryAllStock_rt() {
        //分页数据
        Integer limit = 10;
        //涨幅榜信息
        List<StockUpdownDomain> stockUpdownDomains = stockRtInfoMapper.queryAllStock_rt(lastDate, limit);
        if (stockUpdownDomains == null) {
            //无响应数据
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        return R.ok(stockUpdownDomains);
    }

    @Override
    public R<PageResult<PageInfo>> queryAllPageStockUpdown(Integer page, Integer pageSize) {

        //单表可以直接使用PageHelper，多表另做处理
        PageHelper.startPage(page, pageSize);
        //根据股票交易时间进行查询
        List<StockUpdownDomain> list = stockRtInfoMapper.queryAllStock_rt(lastDate, null);
        if (list == null) {
            return R.error(ResponseCode.ERROR.getMessage());
        }
        //把查询的数据进行封装
        PageInfo<StockUpdownDomain> pageInfo = new PageInfo<>(list);
        //将pageInfo进行二次封装响应给前端
        PageResult pageResult = new PageResult(pageInfo);
        return R.ok(pageResult);
    }

    /**
     * 涨停跌停数据
     *
     * @return
     */
    @Override
    public R<Map<String, List>> queryAllUpDown() {
        //获取有效时间点
        DateTime avableTimePoint = DateTimeUtil.getLastDate4Stock(DateTime.now());
        //根据有效的时间点获取对应日期的开盘和收盘日期
        Date openTime = DateTimeUtil.getOpenDate(avableTimePoint).toDate();
        Date endTime = DateTimeUtil.getCloseDate(avableTimePoint).toDate();
        openTime = DateTime.parse("2022-01-06 09:25:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        endTime = DateTime.parse("2022-01-06 14:25:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        //获取涨停数据
        List<Map> upList = stockRtInfoMapper.queryAllUpDown(openTime, endTime, 1);
        List<Map> downList = stockRtInfoMapper.queryAllUpDown(openTime, endTime, 0);
        //组装数据响应给前端
        Map<String, List> map = new HashMap();
        map.put("upList", upList);
        map.put("downList", downList);
        return R.ok(map);
    }

    /**
     * 下载文件
     *
     * @param page     当前页
     * @param pageSize 每页大小
     * @param response 响应处理
     */
    @Override
    public void queryAllStock_rtToExcel(Integer page, Integer pageSize, HttpServletResponse response) {
        try {
            String fileName = "股票涨跌信息";
            //处理excel文件格式
            response.setContentType("application/vnd.ms-excel");
            //设置编码格式
            response.setCharacterEncoding("utf-8");
            //设置编码
            String name = URLEncoder.encode(fileName, "utf-8");
            //设置默认文件名称
            response.setHeader("content-disposition", "attachment;filename=" + name + ".xlsx");
            //查询股票信息
            //单表可以直接使用PageHelper，多表另做处理
            PageHelper.startPage(page, pageSize);
            //根据股票交易时间进行查询
            List<StockUpdownDomain> list = stockRtInfoMapper.queryAllStock_rt(lastDate, null);
            if (list == null) {
                throw new RuntimeException("下载信息失败！");
            }
            //调用下载工具EasyExcel
            EasyExcel.write(response.getOutputStream(), StockUpdownDomain.class)
                    .sheet(fileName)
                    .doWrite(list);
        } catch (Exception e) {
//            e.printStackTrace();
            log.info("股票excel数据导出异常，当前页：{}，每页大小：{}，异常信息：{}", page, pageSize, e.getMessage());
        }
    }
}
